package impl

import (
	"context"

	"gitee.com/shiwjlinux/vblog01/apps/user"
	"gitee.com/shiwjlinux/vblog01/conf"
	"gitee.com/shiwjlinux/vblog01/ioc"
	"gorm.io/gorm"
)

// 初始化函数
func init() {
	// 注册UserController
	ioc.Controller.Registry(user.AppName, &UserServiceImpl{})
}

func GetService() user.Service {
	return ioc.Controller.Get(user.AppName).(user.Service)
}

var (
	_ user.Service = (*UserServiceImpl)(nil)
	_ ioc.Object   = (*UserServiceImpl)(nil)
)

type UserServiceImpl struct {
	db *gorm.DB
}

// 初始化UserServiceImpl
func (i *UserServiceImpl) Init() error {
	//
	i.db = conf.C().MySQL.GetDB()
	return nil
}

func (i *UserServiceImpl) CreateUser(ctx context.Context,
	in *user.CreateUserRequest,
) (*user.User, error) {
	// 验证参数
	if err := in.Validate(); err != nil {
		return nil, err
	}

	// 密码加密
	if err := in.HashPassword(); err != nil {
		return nil, err
	}

	ins := user.NewUser(in)
	// 入库
	if err := i.db.WithContext(ctx).Create(ins).Error; err != nil {
		return nil, err
	}
	// 密码脱敏
	ins.MaskPassword()
	// 返回ins
	return ins, nil
}

func (i *UserServiceImpl) QueryUser(ctx context.Context,
	in *user.QueryUserRequest,
) (*user.UserSet, error) {
	set := user.NewUserSet()

	query := i.db.Model(user.User{}).WithContext(ctx)
	if in.Username != "" {
		query = query.Where("username = ?", in.Username)
	}
	if err := query.Count(&set.Total).Error; err != nil {
		return nil, err
	}

	if err := query.
		Offset(in.Offset()).
		Limit(in.PageSize).
		Find(&set.Items).Error; err != nil {
		return nil, err
	}

	return set, nil
}
